import { join } from 'path'
import { app } from 'electron'
import { Low } from 'lowdb'
import { JSONFile } from 'lowdb/node'
import fs from 'fs'

// 定义数据类型
interface HttpRequest {
  id: number
  name: string
  method: string
  url: string
  headers: string
  queryParams: string
  bodyType: string
  formData: string
  rawBody: string
  createdAt: string
}

interface DbData {
  requests: HttpRequest[]
  lastId: number
}

class Database {
  private db: Low<DbData>
  private initialized: boolean = false

  constructor() {
    // 获取应用程序的安装根目录
    const appPath = app.getPath('exe')
    const appDir = join(appPath, '..')
    
    // 创建config目录
    const configDir = join(appDir, 'config')
    if (!fs.existsSync(configDir)) {
      fs.mkdirSync(configDir, { recursive: true })
    }
    
    // 设置数据库文件路径
    const dbFile = join(configDir, 'http-history.json')
    
    // 确保数据文件存在
    if (!fs.existsSync(dbFile)) {
      fs.writeFileSync(dbFile, JSON.stringify({ requests: [], lastId: 0 }))
    }

    const adapter = new JSONFile<DbData>(dbFile)
    this.db = new Low(adapter, { requests: [], lastId: 0 })
  }

  private async init() {
    if (!this.initialized) {
      await this.db.read()
      this.initialized = true
    }
  }

  async saveRequest(data: any): Promise<number> {
    await this.init()
    
    // 增加 ID
    const id = (this.db.data.lastId || 0) + 1
    this.db.data.lastId = id

    // 保存请求
    this.db.data.requests.unshift({
      id,
      name: data.name,
      method: data.method,
      url: data.url,
      headers: JSON.stringify(data.headers),
      queryParams: JSON.stringify(data.queryParams),
      bodyType: data.bodyType,
      formData: JSON.stringify(data.formData),
      rawBody: data.rawBody,
      createdAt: data.createdAt
    })

    // 限制保存最近100条记录
    if (this.db.data.requests.length > 100) {
      this.db.data.requests = this.db.data.requests.slice(0, 100)
    }

    await this.db.write()
    return id
  }

  async loadRequests(): Promise<any[]> {
    await this.init()
    
    try {
      return this.db.data.requests.map(row => ({
        ...row,
        headers: JSON.parse(row.headers || '[]'),
        queryParams: JSON.parse(row.queryParams || '[]'),
        formData: JSON.parse(row.formData || '[]')
      }))
    } catch (error) {
      console.error('Error loading requests:', error)
      return []
    }
  }

  async deleteRequest(id: number): Promise<void> {
    await this.init()
    
    this.db.data.requests = this.db.data.requests.filter(req => req.id !== id)
    await this.db.write()
  }

  async updateRequest(data: any): Promise<void> {
    await this.init()
    
    // 找到要更新的记录索引
    const index = this.db.data.requests.findIndex(req => req.id === data.id)
    if (index === -1) {
      throw new Error('Record not found')
    }

    // 更新记录
    this.db.data.requests[index] = {
      id: data.id,
      name: data.name,
      method: data.method,
      url: data.url,
      headers: JSON.stringify(data.headers),
      queryParams: JSON.stringify(data.queryParams),
      bodyType: data.bodyType,
      formData: JSON.stringify(data.formData),
      rawBody: data.rawBody,
      createdAt: data.createdAt
    }

    await this.db.write()
  }
}

// 创建单例实例
const database = new Database()

// 导出数据库方法
export const saveRequest = (data: any) => database.saveRequest(data)
export const loadRequests = () => database.loadRequests()
export const deleteRequest = (id: number) => database.deleteRequest(id)
export const updateRequest = (data: any) => database.updateRequest(data)